layui.define(['jquery','admin','layer','table','http'],function (exports) {
    var $ = layui.jquery;
    var admin = layui.admin;
    var layer = layui.layer;
    var table = layui.table;
    var http = layui.http;

    var padding = function(s, len) {
        len = len - (s + '').length;
        for (var i = 0; i < len; i++) { s = '0' + s; }
        return s;
    };
    var indexOf = function(str,c) {
        for(var i=0;i<str.length;i++){
            if(str[i] == c){
                return i;
            }
        }
        return -1;
    };
    var getInt = function(s){
        if(!s){return 0;}
        var i = 0;
        for(;i<s.length;i++){
           if(s[i] != 0){
               break;
           }
        }
        return parseInt(s.substring(i));
    };
    var stringToDate = function(dateStr){
        if(typeof dateStr === 'object' && "getTime" in dateStr){
            dateStr.setHours(0);
            dateStr.setMinutes(0);
            dateStr.setSeconds(0);
            dateStr.setMilliseconds(0);
            return dateStr;
        }
        var seperator = "-";
        if(dateStr.indexOf("/")>0){
            seperator = "/";
        }
        var dateArr = dateStr.split(seperator);
        var year = parseInt(dateArr[0]);
        var month = parseInt(dateArr[1]);
        var day = parseInt(dateArr[2]);
        var date = new Date(year,month -1,day);
        return date;
    };
    var stringToDateTime = function(dateStr){
        var seperator = "-";
        if(dateStr.indexOf('-')>0){
            seperator = "/";
        }
        var dateArr = dateStr.split(seperator);
        var year = parseInt(dateArr[0]);
        var month = parseInt(dateArr[1]);
        var day = parseInt(dateArr[2]);
        var hour = 0;
        var minute = 0;
        var second = 0;

        dateArr = (dateStr.split(" ")[1]).split(":");
        if(!!dateArr && dateArr.length>=3) {
            hour = parseInt(dateArr[0]);
            minute = parseInt(dateArr[1]);
            second = parseInt(dateArr[2]);
        }
        var date = new Date(year,month -1,day, hour, minute, second);
        return date;
    };
    var getFormVal = function (elem) {
        var obj={};
        var jElem = typeof elem == "string" ? $(elem) : elem;
        jElem.find("select[name]").each(function(i){
            var value= $(this).val();
            var name= $(this).attr('name');
            obj[name]=value;
        });
        jElem.find("input[name]").each(function(i){
            var value= $(this).val();
            var name= $(this).attr('name');
            obj[name]=value;
        });
        jElem.find("textarea[name]").each(function(i){
            var value= $(this).val();
            var name= $(this).attr('name');
            obj[name]=value;
        });
        return obj;
    };
    var userAgent = navigator.userAgent;
    var browser = {};
    browser.isIE = function () {
        return userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && userAgent.indexOf("Opera") < 0; //判断是否IE<11浏览器
    }();
    browser.isEdge = function () {
        var that = this;
        return userAgent.indexOf("Edge") > -1 && !browser.isIE; //判断是否IE的Edge浏览器
    }();
    browser.isIE11 = function () {
        return userAgent.indexOf('trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    }();
    browser.isFirefox = function () {
        return userAgent.indexOf("Firefox") > 0;
    }();
    browser.isSafari = function(){
        return userAgent.indexOf("Safari") > 0 && userAgent.indexOf("Chrome") < 0;
    }();
    browser.isChrome = function () {
        return userAgent.indexOf("Chrome") > 0;
    }();
    browser.isOpera = function () {
        return userAgent.indexOf("Opera") > -1;
    }();
    browser.IEVersion = function () {
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        return parseFloat(RegExp["$1"]);
    }();

    var treeTable = {
        reload: function (tableId,url,where,callback) {
            var mData = [];
            // 对数据进行排序
            var sort = function (s_pid, data) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i].pid == s_pid) {
                        var len = mData.length;
                        if (len > 0 && mData[len - 1].id == s_pid) {
                            mData[len - 1].isParent = true;
                        }
                        mData.push(data[i]);
                        sort(data[i].id, data);
                    }
                }
            };
            http.get(url,where,function(res){
                if(res.ok) {
                    var tmpData = sort(0, res.data);
                    table.reload(tableId, {data: tmpData});
                }
                callback && typeof callback === 'function' && callback(res);
            })
        }
    };

    var listToOptions = function (params) {
        var list = params.list;
        var currValue = params.currValue;
        var extraFields = params.extraFields;
        params.codeKey = params.codeKey || 'code';
        params.textKey = params.textKey || 'name';
        var s = "";
        if(list && list.length && list.length > 0) {
            if(typeof list[0] !== 'object'){
                for (var i = 0; i < list.length; i++) {
                    var codeValue = list[i] || '';
                    if (currValue && currValue == codeValue) {
                        s = s + '<option selected value="' + codeValue + '">' + codeValue + '</option>';
                    } else {
                        s = s + '<option value="' + codeValue+ '">' + codeValue + '</option>';
                    }
                }
            }else {
                for (var i = 0; i < list.length; i++) {
                    var item = list[i];
                    if(!item){ continue; }
                    var codeValue = item[params.codeKey] || '';
                    var textValue = item[params.textKey] || '';
                    if (currValue && currValue == codeValue) {
                        s = s + '<option selected value="' + codeValue +'" ';
                    } else {
                        s = s + '<option value="' + codeValue + '" ';
                    }
                    if(extraFields) {
                        for (var j = 0; j < extraFields.length; j++) {
                            var f = extraFields[j];
                            if (f) {
                                s = s + f + '="' + (item[f] || '') + '" ';
                            }
                        }
                    }
                    s = s + '>' + (textValue || codeValue) + '</option>';
                }
            }
        }
        return s;
    };

    var listToSelect = function (params) {
        if(!params || !params.elemName || !params.list){
            return "";
        }
        var s = '<select name="' + params.elemName + '" ' + (params.attr || '');
        return s + '>' + listToOptions(params) + '</select>';
    };

    var  setOptionByListName = function(listName,selector,callBack){
        http.getCodeList(listName,function(res) {
            if (res.ok) {
                tools.select.options(selector, res.data);
            }
            callBack && typeof callBack == 'function' && callBack(res);
        });
    };

    var setOptionsByList = function (elem, list, currValue) {
        if (!list) {
            return;
        }
        var localElem = undefined;
        if (elem || elem.hasOwnProperty || elem instanceof layui.jquery) {
            localElem = elem;
        } else {
            localElem = $(elem);
        }
        if (!currValue) {
            currValue = localElem.val() || '';
        }
        var defaultOption = localElem.find('option[data-default]').clone();
        var codeKey = localElem.attr("data-codeKey") || localElem.attr("data-valueKey") || "code";
        var textKey = localElem.attr("data-textKey") || "name";
        var extraFields = (localElem.attr("data-extraFields") || "").split(",");
        localElem.empty();
        var s = listToOptions({
            list: list,
            codeKey: codeKey,
            textKey: textKey,
            currValue: currValue,
            extraFields: extraFields
        });

        localElem.append(defaultOption);
        localElem.append(s);
    };

    var tools = {
        param:{},
        select: {
            codes: setOptionByListName
            ,options: setOptionsByList
            ,deptCodeOptions: function (elem) {
                var deptCodeList = http.getDeptCodeList();
                var tmpCode = "";
                if(deptCodeList && deptCodeList.length > 0){
                    tmpCode = deptCodeList[0].code;
                }
                tools.select.options(elem,deptCodeList,tmpCode);
            }
            ,listToOptions: listToOptions
            ,listToSelect: listToSelect
        }
        ,formVal: function (elem,json) {
            if(json){
                return setFormVal(elem,json);
            }else{
                return getFormVal(elem);
            }

        }
        ,isEmpty: function (value,showMsg) {
            var reg = /[\S]+/;
            if(!value){
                return true;
            }
            if(typeof value === "string") {
                if (!reg.test(value)) {
                    return true;
                }
            }
            if(typeof value.length != "undefined"){
                if(value.length === 0){
                    return true;
                }
            }
        }
        ,browser: browser
        ,treeTable: treeTable
        ,getDataMax: function(data,fieldName){
            var valMax = 0;
            if(!data || data.length <= 0){
                return valMax;
            }
            for(var i=0;i<data.length;i++){
                var val = data[i][fieldName];
                if(val > valMax){
                    valMax = val;
                }
            }
            return valMax;
        }
        ,getSortMax: function(data){
            var valMax = 0;
            if(!data || data.length <= 0){
                return valMax;
            }
            for(var i=0;i<data.length;i++){
                if(!data[i][table.config.rowStatusName]) {
                    var val = data[i]['sort'];
                    if (val > valMax) {
                        valMax = val;
                    }
                }
            }
            return valMax;
        }
        // 封装layer.open
        ,open: function (param) {
            if (!param.area) {
                param.area = (param.type == 2) ? ['360px', '300px'] : '360px';
            }
            if (!param.skin) {
                param.skin = 'layui-layer-admin';
            }
            if (!param.offset) {
                param.offset = '100px';
            }
            if (param.fixed == undefined) {
                param.fixed = false;
            }
            param.resize = param.resize != undefined ? param.resize : true;
            param.shade = param.shade != undefined ? param.shade : .1;
            if (param.url) {
                param.type = 1;
                var sCallBack = param.success;
                param.success = function (layero, index) {
                    admin.showLoading(layero);
                    sCallBack ? sCallBack(layero, index) : '';
                    $(layero).children('.layui-layer-content').load(param.url, function () {
                        admin.removeLoading(layero);
                    });
                };
            }
            var doneCallback = param.done;
            param.done = function(){
              tools.param = null;
                doneCallback && typeof doneCallback === 'function' && doneCallback();
            };
            return layer.open(param);
        }
        ,focusOther: function(inputs,thatObj,flag){
            if(!inputs || !thatObj){return;}
            var idx = inputs.index(thatObj);
            var colCount = 31;
            if(flag == 37 || flag == 'prev') {  //左箭头
                if (idx > 0) {
                    inputs[idx - 1].focus();
                }
            }else if(flag == 38 || flag == 'prevRow'){ //上箭头
                if(idx-colCount > 0){
                    inputs[idx-colCount].focus();
                }
            } else if(flag == 13 || flag == 39 || flag == 'next') { //回车键，右箭头
                if (idx != inputs.length - 1) {
                    inputs[idx + 1].focus();
                }
            }else if(flag == 40 || flag == 'nextRow'){ //向下箭头
                if(idx+colCount < inputs.length - 1){
                    inputs[idx+colCount].focus();
                }
            }
        }
        ,getWeekName: function(week){
            switch (week) {
                case 1:
                    return '一';
                case 2:
                    return '二';
                case 3:
                    return '三';
                case 4:
                    return '四';
                case 5:
                    return '五';
                case 6:
                    return '六';
                case 0:
                    return '天';
            }
        }
        ,padding: padding
        ,formatDateTime: function(date,spliter){
            var d = date || (new Date());
            if(typeof(date)=="string"){d = new Date(date.replace(/-/g,'/'))}
            spliter = spliter || '';
            var spliter2 = !spliter ? '':':';
            var yy = d.getFullYear();
            var MM = d.getMonth()+1;
            var dd = d.getDate();

            var hh = d.getHours();
            var mm = d.getMinutes();
            var ss = d.getSeconds();

            return yy+ spliter + padding(MM,2) + spliter + padding(dd,2) + (!spliter2 ? '':' ') + padding(hh,2) + spliter2 + padding(mm,2) + spliter2 + padding(ss,2);
        }
        ,formatDate: function(date,spliter){
            var d = date || (new Date());
            if(typeof(date)=="string"){d = new Date(date.replace(/-/g,'/'))}
            spliter = spliter || '';
            var yy = d.getFullYear();
            var mm = d.getMonth()+1;
            var dd = d.getDate();

            return yy+ spliter + padding(mm,2) + spliter + padding(dd,2);
        }
        ,formatTime: function(date,spliter){
            var d = date || (new Date());
            if(typeof(date)=="string"){d = new Date(date.replace(/-/g,'/'))}
            spliter = spliter || '';
            var hh = d.getHours();
            var mm = d.getMinutes();
            var ss = d.getSeconds();

            return padding(hh,2) + spliter + padding(mm,2) + spliter + padding(ss,2);
        }
        ,formatYearMonth: function(date,spliter){
            var d = date || (new Date());
            if(typeof(date)=="string"){d = new Date(date.replace(/-/g,'/'))}
            spliter = spliter || '';
            var yy = d.getFullYear();
            var mm = d.getMonth()+1;
            var dd = d.getDate();

            return yy+ spliter + padding(mm,2);
        }
        ,formatYYMM: function(date,spliter){
            var d = date || (new Date());
            if(typeof(date)=="string"){d = new Date(date.replace(/-/g,'/'))}
            spliter = spliter || '';
            var yy = d.getFullYear();
            var mm = d.getMonth()+1;

            return (yy+'').slice(-2)+ spliter + padding(mm,2);
        }
        ,stringToDate: stringToDate
        ,stringToDateTime: stringToDateTime
        ,todayStr: function(){
            return tools.formatDate(new Date(),"-");
        }
        ,lastDay: function(date){
            if(typeof date === 'string'){
                date = stringToDate(date);
            }
            var yy = date.getFullYear();
            var mm = date.getMonth()+1;
            return (new Date(yy,mm,0)).getDate();
        }
        ,dateAdd: function(date,interval,num){
            var d;
            if(typeof date === 'string'){
                d=stringToDate(date);
            }else if(typeof date ==='object'){
                d=date;
            }
            if(!date){
                d = new Date();
            }
            if(!num){
                return d;
            }
            switch (interval || 'd') {
                case 'y': d.setFullYear(d.getFullYear()+num);break;
                case 'm': d.setMonth(d.getMonth()+num);break;
                case 'd': d.setDate(d.getDate()+num);break;
                case 'w': d.setDate(d.getDate()+7*num);break;
                case 'h': d.setHours(d.getHours()+num);break;
                case 'mi': d.setMinutes(d.getMinutes()+num);break;
                case 's': d.setSeconds(d.getSeconds()+num);break;
                case 'ms': d.setMilliseconds(d.getMilliseconds()+num);break;
            }
            return d;
        }
        ,dateDiff: function(interval,date1,date2){
            var long = date2.getTime() - date1.getTime();
            switch(interval.toLowerCase()){
                case "y": return parseInt(date2.getFullYear()-date1.getFullYear());break;
                case "m": return parseInt((date2.getFullYear()-date1.getFullYear())*12+(date2.getMonth()-date1.getMonth()));break;
                case "d": return parseInt(long/1000/60/60/24);break;
                case "w": return parseInt(long/1000/60/60/24/7);break;
                case "h": return parseInt(long/1000/60/60);break;
                case "mi": return parseInt(long/1000/60);break;
                case "s": return parseInt(long/1000);
                case "ms": return parseInt(long);
            }
        },
    };
    exports('tools',tools);
})